﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using FFmpegVideoClip.Configuration;
using FFmpegVideoClip.Lib;
using FFmpegVideoClip.Lib.AdvancedFragmentProcessor;
using FFmpegVideoClip.Mode;

namespace FFmpegVideoClip.windows
{
    /// <summary>
    /// FlowSelect.xaml 的交互逻辑
    /// </summary>
    public partial class FlowSelect : Window
    {
        private static FlowSelect? Instance;
        public static void ShowWindow(bool IsFilter = false)
        {
            if(Instance !=null)
            {
                Instance.Activate();
                return;
            }
            Instance = new FlowSelect(IsFilter);
            Instance.Show();
        }

        public static readonly DependencyProperty ShowDataProperty =
            DependencyProperty.Register("AllowSelectModules", typeof(AdvancedParametersSchemeModule[]), typeof(FlowSelect), new PropertyMetadata(null));

        public AdvancedParametersSchemeModule[] AllowSelectModules
        {
            get { return (AdvancedParametersSchemeModule[])GetValue(ShowDataProperty); }
            set { SetValue(ShowDataProperty, value); }
        }
        private FlowSelect() { }
        private FlowSelect(bool IsFilter = false)
        {
            InitializeComponent();
            Closed += (s, e) => Instance = null;
            if (IsFilter)
            {
                AllowSelectModules = Config.Instance.SchemeModules
                     .Where(p => !(p.GetParametersSign(ParametersSign.STime, out _) || p.GetParametersSign(ParametersSign.ETime, out _)))
                     .ToArray();
            }
            else AllowSelectModules = Config.Instance.SchemeModules.ToArray();
        }

        private void SelectItem_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                FrameworkElement? draggedItem = (FrameworkElement)e.OriginalSource;
                if (draggedItem is null)
                    return;
                while (draggedItem!.DataContext is not AdvancedParametersSchemeModule)
                {
                    draggedItem = VisualTreeHelper.GetParent(draggedItem) as FrameworkElement;
                    if (draggedItem is null)
                        return;
                }
                try
                {
                    DragDrop.DoDragDrop(draggedItem, new DataObject(new DragDropData(typeof(AdvancedParametersSchemeModule), typeof(ListBox), "FlowSelectWindows", SelectItem, draggedItem.DataContext)), DragDropEffects.Copy);
                }
                catch(System.Exception ex) 
                {
                    LogManage.WriteExceptionInfo($"拖拽[{((AdvancedParametersSchemeModule)draggedItem.DataContext).SchemeName}]异常报错", ex);
                }
                
            }
        }

    }
}
